const mssql = require('mssql')
const sqlConfig = {
  user: 'sa',
  password: '123456',
  database: 'mi',
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: true // change to true for local dev / self-signed certs
  }
}

const sql = (str) => {
  return new Promise(async (resolve, reject) => {
    try {
      await mssql.connect(sqlConfig);
    } catch (err) {
      return resolve({
        status: 400,
        msg: "数据库连接失败"
      })
    }
    try {
      const res = await mssql.query(str)
      resolve({
        recordsets: res.recordsets,
        recordset: res.recordset,
        output: res.output,
        rowsAffected: res.rowsAffected[0]
      })
    } catch (err) {
      resolve({
        status: 400,
        msg: "sql语句错误,检查表名，字段名是否出错"
      })
    }
  })
}

module.exports = {
  sql
}